package panda.query.tree;

import java.util.List;

import panda.file.Page;
import panda.query.scan.Scanner;
import panda.query.struct.Attribute;
import panda.query.util.GroupByComparator;
import panda.query.util.MergeSorter;
import panda.record.Schema;
import panda.record.TableToken;
import panda.transaction.Transaction;

public class SortNode implements QueryTreeNode{
	private QueryTreeNode q;
	private List<Attribute> attrs;
	Transaction tx;
	
	public SortNode(QueryTreeNode q, List<Attribute> attrs, Transaction tx) {
		this.q = q;
		this.attrs = attrs;
		this.tx = tx;
	}
	
	public SortNode(QueryTreeNode q, List<Attribute> attrs, List<Integer> order, Transaction tx) {
		this.q = q;
		this.attrs = attrs;
		this.tx = tx;
	}

	public Scanner open() {
//		TempTable t = new TempTable(q.getSchema(), tx);
//		t.copyFrom(q.open());
//		t.sort(attrs);
		return MergeSorter.sortTable(q, attrs, new GroupByComparator(attrs), tx);
	}
	
	public int blockAccessed() {
		double t = (double)(Page.BLOCK_SIZE)/TableToken.getTupleLength(q.getSchema());
		return (int)(Math.ceil(q.outputSize() / t));
	}

	public int distinctSize(Attribute attr) {
		return q.distinctSize(attr);
	}

	public int outputSize() {
		return q.outputSize();
	}

	public Schema getSchema() {
		return q.getSchema();
	}
	
}
